#/bin/bash

if [ $# -lt 1 ]; then
	echo "Usage: $0 path_to_bootloader"
	exit -1
fi

if [ ! -e $1 ]; then
	echo "Image $1 isn't exist"
	exit -1
fi

IMG=$1

DISK=sdb
ST=`cat /proc/partitions | grep "\<$DISK\>" | awk -F " " '{print $3}'`
EXEC=.run.sh

S1=$[$ST * 10 / 100 / 1024]M
S2=$[$ST * 10 / 100 / 1024]M
S3=$[$ST * 50 / 100 / 1024]M
S5=$[$ST * 10 / 100 / 1024]M
S6=$[$ST * 10 / 100 / 1024]M

cat > $EXEC << END
#!/bin/sh
dd if=/dev/zero of=/dev/$DISK bs=512 count=1
fdisk /dev/$DISK << "EOF"
n
p
1

+$S1
n
p
2

+$S2
n
p
3

+$S3
n
e


n

+$S5
n

+$S6
n


a
1
w
q
EOF
END

echo "formart disk"

sh $EXEC
rm $EXEC

mkfs.ext3 /dev/"$DISK"1
mkfs.ext3 /dev/"$DISK"2
mkfs.ext3 /dev/"$DISK"3
mkfs.ext3 /dev/"$DISK"5
mkfs.ext3 /dev/"$DISK"6
mkfs.ext3 /dev/"$DISK"7

echo "formart disk done"


echo "install bootloader"

cat /usr/lib/syslinux/mbr.bin > /dev/$DISK
mount /dev/"$DISK"1 /mnt
mkdir -p /mnt/syslinux/
cat > /mnt/syslinux/syslinux.cfg << EOF

TIMEOUT 50
UI menu.c32
SERIAL 0 115200

LABEL ntsec
	MENU LABEL NTSec
	LINUX ../ntsec/vmlinuz
	INITRD ../ntsec/initrd.gz
	APPEND rw root=/dev/ram init=/sbin/init console=ttyS0,115200n8 acpi=off

LABEL bootloader
	MENU LABEL Bootloader
	LINUX ../bootloader/vmlinuz
	APPEND console=ttyS0,115200n8 console=tty1


LABEL hdt
	MENU LABEL HDT (Hardware Detection Tool)
	COM32 hdt.c32
                 
LABEL reboot
	MENU LABEL Reboot
	COM32 reboot.c32
                              
LABEL off
	MENU LABEL Power Off
	COMBOOT poweroff.com

EOF


extlinux -i /mnt/syslinux
cp -r /usr/lib/syslinux/* /mnt/syslinux/
mkdir -p /mnt/bootloader
cp $IMG /mnt/bootloader/vmlinuz
umount /mnt

echo "install bootloader done"

